import { notification } from 'antd';
import { history } from 'umi';
import { extend } from 'umi-request';

import { BASE_URL } from '@/constants/global.const';
import StorageManager from './StorageManager';

const codeMessage = {
  200: '服务器成功返回请求的数据。',
  201: '新建或修改数据成功。',
  202: '一个请求已经进入后台排队（异步任务）。',
  204: '删除数据成功。',
  400: '发出的请求有错误，服务器没有进行新建或修改数据的操作。',
  401: '用户没有权限（令牌、用户名、密码错误）。',
  403: '用户得到授权，但是访问是被禁止的。',
  404: '发出的请求针对的是不存在的记录，服务器没有进行操作。',
  405: '请求方法不被允许。',
  406: '请求的格式不可得。',
  410: '请求的资源被永久删除，且不会再得到的。',
  422: '当创建一个对象时，发生一个验证错误。',
  500: '服务器发生错误，请检查服务器。',
  502: '网关错误。',
  503: '服务不可用，服务器暂时过载或维护。',
  504: '网关超时。',
};

const redirectToLogin = () => {
  const { query = {} } = history.location;
  const { redirect } = query;
  if (window.location.pathname !== '/login' && !redirect) {
    StorageManager.removeCookie('token');
    StorageManager.clearLocalStorageSync();
    history.replace({ pathname: '/login' });
  }
};

const errorHandler = (error: { response: any }) => {
  const { response } = error;
  if (response && response.status) {
    const { status, url, statusText } = response;
    const errorText = codeMessage[status as keyof typeof codeMessage] || statusText;
    if (status === 403 || status === 401) {
      // 退出之前的页面路由
      // 跳转到登录地址
      redirectToLogin();
    } else {
      notification.error({
        message: `请求错误${status}：${url}`,
        description: errorText,
      });
    }
  } else if (!response) {
    notification.error({
      description: '您的网络发生异常，请稍后重试',
      message: '网络异常',
    });
  }
  return Promise.reject(error.response);
};

const request = extend({
  errorHandler, // 默认错误处理
  timeout: 15000, // 超时：15s
  credentials: 'omit', // 默认请求是否带上cookie
});

request.interceptors.response.use(async (response, options): Promise<any> => {
  if (options.responseType === 'blob') {
    return response;
  }
  const { code, message } = await response.clone().json();
  if (code === 122100101 || code === 122104110) {
    notification.error({
      description: '请求失败',
      message,
    });
    // 跳转到登录地址
    redirectToLogin();
  }
  return response;
});
request.interceptors.request.use((url, options): any => {
  const { method, requestType } = options;
  const token = StorageManager.getCookie('token');
  let headers: Record<string, any> = {
    ticket: token,
  };
  if (['get', 'post', 'put', 'delete'].includes(method || '')) {
    if (requestType !== 'form') {
      headers = {
        ...headers,
        Accept: 'application/json',
        'Context-Type': 'applications/json;charset=utf-8',
      };
    }

    return {
      url: url.startsWith('http') ? url : `${BASE_URL}${url}`,
      options: {
        ...options,
        headers,
      },
    };
  }
  return false;
});

export default request;
